﻿// 与原 stomp 版保持一致的对外 API：ensureConnected / disconnect / onAnyMessage / setAuthToken
// 订阅主题可继续用你们的 NOTIFICATION_STR 常量（通常带 /topic 前缀）

import SseCenter from "@/core/sse-center";
import { NOTIFICATION_STR } from "@/utils/const.js";

const PROJECT = (typeof __PROJECT_NAME__ !== "undefined" && __PROJECT_NAME__) || "";
const FORCE_ENABLE = import.meta.env.VITE_MSG_ENABLE === "true";
const ENABLED = FORCE_ENABLE || ["rent_qyz_ope", "rent_qyz_business"].includes(PROJECT);

// 常量里常带 "/topic/..."；这里裁掉 "/topic/"，由 VITE_SSE_BASE 再拼，避免重复
const RAW_TOPICS = [
  NOTIFICATION_STR.NOTIFICATION, // 例："/topic/notification"
  NOTIFICATION_STR.ANNOUNCEMENT, // 例："/topic/announcement/ope"（按你们实际目标）
];
const SUB_TOPICS = RAW_TOPICS.map(t =>
  String(t || "")
    .replace(/^\/?topic\//, "")
    .replace(/^\/+/, "")
);

// 如果你“完全不需要自定义请求头”，可删掉 buildHeaders；若以后切回 header 鉴权，直接恢复即可
const sse = new SseCenter({
  debug: import.meta.env.DEV,
  // buildHeaders: () => ({
  //   Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
  //   "X-Tenant-Id": String(localStorage.getItem("tenantId") || ""),
  // }),
});

let subscribed = false;
let started = false;

const listeners = new Set();
function emitAll(payload) {
  for (const fn of listeners) {
    try {
      fn(payload);
    } catch (e) {
      console.error("[MsgCenter] listener error:", e);
    }
  }
}

function registerDefaultSubscriptions() {
  if (subscribed) return;
  SUB_TOPICS.forEach((sub, i) => {
    const original = RAW_TOPICS[i]; // 对外回传原始 topic，避免业务侧改动
    sse.subscribe(sub, (data, raw) => {
      console.log("[SSE] <-", original, data);
      emitAll({ topic: original, data, raw });
    });
  });
  subscribed = true;
}

// —— 对外：事件监听 —— //
export function onAnyMessage(cb) {
  listeners.add(cb);
  return () => listeners.delete(cb);
}

// —— 对外：设置 token（用于 URL 鉴权时，或未来切回 header 鉴权） —— //
export function setAuthToken(token) {
  if (token) localStorage.setItem("token", token);
  else localStorage.removeItem("token");
  if (started) {
    sse.stop();
    setTimeout(() => {
      if (started) sse.start();
    }, 0); // 热重连以带上新 token
  }
}

// （可选）设置租户等上下文
export function setTenantId(tenantId) {
  if (tenantId) localStorage.setItem("tenantId", tenantId);
  else localStorage.removeItem("tenantId");
  if (started) {
    sse.stop();
    setTimeout(() => {
      if (started) sse.start();
    }, 0);
  }
}

// —— 对外：启动/停止 —— //
export function ensureConnected() {
  if (!ENABLED) {
    console.log("[MSG] MessageCenter disabled for", PROJECT);
    return;
  }
  registerDefaultSubscriptions();
  sse.start();
  started = true;
}
export function disconnect() {
  started = false;
  sse.stop();
}

// —— 初始化（main.js 里调用一次即可） —— //
export function setupMessageCenter(_app) {
  if (!ENABLED) {
    console.log("[MSG] MessageCenter disabled for", PROJECT);
    return;
  }
  registerDefaultSubscriptions();
  console.log("[MSG] MessageCenter ready for", PROJECT);
}

// 可选：需要时暴露底层实例
// export function getSseClient() { return sse; }
